package cn.com.connext.scrm.web.rest;

import cn.com.connext.scrm.domain.master.LorealCode;
import cn.com.connext.scrm.service.LorealCodeService;
import cn.com.connext.scrm.service.dto.JsonResult;
import com.connext.common.web.rest.BaseResource;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 第三方调用接口
 */
@RestController
@RequestMapping("/api/lorealcode/")
public class LorealCodeResource extends BaseResource {
    private final Logger logger = LoggerFactory.getLogger(LorealCodeResource.class);

    @Autowired
    private LorealCodeService lorealCodeService;

    public LorealCodeResource() {
        super(" LorealCode");
    }

    private Lock lock = new ReentrantLock();

    /**
     * 校验code是否可以使用
     */
    @ApiOperation(value = "checkCode", notes = "校验code是否可以使用")
    @PostMapping(value = "/checkCode")
    public JsonResult checkCode(@RequestBody LorealCode code){
        JsonResult result = new JsonResult();
        lock.lock();
      try{
           LorealCode codeEntity = lorealCodeService.checkCode(code);
           if(codeEntity == null){
                result.setMessage("此校验码无效，请输入正确的校验码!");
                result.setState(-1);
           }else{
               if(codeEntity.getIsUse() ==1){
                   result.setMessage("此校验码已被使用，请重新输入!");
                   result.setState(-1);
               }else{
                   codeEntity.setUseUnionId(code.getUseUnionId());
                   lorealCodeService.update(codeEntity);
                   result.setMessage("校验通过");
                   result.setState(0);
               }
           }
        } catch (Exception e) { logger.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统异常");
        }finally {
          lock.unlock();
      }
        return result;
    }

    /**
     * 校验code是否可以使用
     */
    @ApiOperation(value = "addCode", notes = "添加600个随机码")
    @PostMapping(value = "/addCode")
    public JsonResult addCode(){
        JsonResult result = new JsonResult();
        lock.lock();
        try{
            lorealCodeService.batchAdd();
            result.setState(0);
            result.setMessage("添加成功");
        } catch (Exception e) { logger.error("e:{}", e);
            result.setState(-1);
            result.setMessage("系统异常");
        }finally {
            lock.unlock();
        }
        return result;
    }
}

